package com.zkflzl.store.manage;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zkflzl.store.model.entity.Msg;
import com.zkflzl.store.service.MsgService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@Component
public class MsgScheduler {
    @Resource
    private MsgService msgService;

    // 每隔15分钟执行一次
    @Scheduled(fixedRate = 100 * 60 * 15) // 单位为毫秒
    public void checkUnreadMessagesAndSendSms() {
        // 检查是否有消息超过3小时未读取
        Date currentTime = new Date();
        QueryWrapper<Msg> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .ge("createTime", DateUtils.addHours(currentTime, -3)) // 查询3小时之前的消息
                .eq("status", 0);    // 未读
        List<Msg> msgList = msgService.list(queryWrapper);

        // 发送短信给管理员
        for (Msg message : msgList) {
            // TODO: 调用发送短信的方法
            log.println("发送短信给管理员：" + message.getMsg());
            // 更新消息状态为已读
            message.setStatus(1);
            msgService.updateById(message);
        }
    }
}